<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { http } from '../utils/http'
import { API_CONFIG } from '../config/api'

const router = useRouter()

const form = ref({
  summary: '',
  content: ''
})

const loading = ref(false)
const titleLoading = ref(false)
const recommendedTitles = ref<string[]>([])
const showTitleOptions = ref(false)

const rules = {
  summary: [
    { required: true, message: '请输入帖子标题', trigger: 'blur' },
    { min: 5, max: 100, message: '标题长度在 5 到 100 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入帖子内容', trigger: 'blur' },
    { min: 10, message: '内容至少需要 10 个字符', trigger: 'blur' }
  ]
}

const formRef = ref()

// 获取推荐标题
const getRecommendedTitles = async () => {
  if (!form.value.content.trim()) {
    ElMessage.warning('请先输入帖子内容')
    return
  }
  
  try {
    titleLoading.value = true
    
    // 使用原生fetch进行POST请求，设置30秒超时
    const controller = new AbortController()
    const timeoutId = setTimeout(() => controller.abort(), 50000) // 30秒超时
    
    const response = await fetch(`${API_CONFIG.BASE_URL}/api/posts/recommend_title`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        ...(localStorage.getItem('token') && { 'Authorization': `Bearer ${localStorage.getItem('token')}` })
      },
      body: JSON.stringify({
        content: form.value.content
      }),
      signal: controller.signal
    })
    
    clearTimeout(timeoutId)
    
    if (!response.ok) {
      throw new Error(`HTTP Error: ${response.status} ${response.statusText}`)
    }
    
    const data = await response.json()
    // 从返回的对象数组中提取title字段
    recommendedTitles.value = (data.titles || []).map((item: any) => 
      typeof item === 'string' ? item : item.title
    )
    showTitleOptions.value = true
    
    if (recommendedTitles.value.length === 0) {
      ElMessage.info('暂无推荐标题，请手动输入')
    }
  } catch (error) {
      console.error('获取推荐标题失败:', error)
      ElMessage.error('获取推荐标题失败，请重试')
  } finally {
    titleLoading.value = false
  }
}

// 选择推荐标题
const selectTitle = (title: string) => {
  form.value.summary = title
  showTitleOptions.value = false
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    // 如果标题为空，先获取推荐标题
    if (!form.value.summary.trim()) {
      await getRecommendedTitles()
      return
    }
    
    await formRef.value.validate()
    loading.value = true
    
    // 调用真实的创建帖子API
    const response = await http.post(`${API_CONFIG.BASE_URL}/posts`, form.value)
    
    ElMessage.success('帖子创建成功')
    router.push('/posts')
  } catch (error) {
    console.error('创建帖子失败:', error)
    ElMessage.error('创建帖子失败，请重试')
  } finally {
    loading.value = false
  }
}

const handleCancel = () => {
  router.push('/posts')
}
</script>

<template>
  <div class="create-post">
    <div class="page-header">
      <h1>发布新帖子</h1>
      <p>分享你的想法和经验</p>
    </div>

    <el-card class="form-card">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        class="post-form"
      >
        <el-form-item label="标题" prop="summary">
          <div class="title-input-container">
            <el-input
              v-model="form.summary"
              placeholder="请输入帖子标题"
              maxlength="100"
              show-word-limit
              clearable
              class="title-input"
            />
            <el-button
              type="primary"
              :loading="titleLoading"
              @click="getRecommendedTitles"
              class="smart-title-btn"
            >
              <el-icon><MagicStick /></el-icon>
              {{ titleLoading ? '生成中...' : '智能标题' }}
            </el-button>
          </div>
          
          <!-- 推荐标题选择框 -->
          <div v-if="showTitleOptions" class="title-options">
            <div class="title-options-header">
              <span>推荐标题：</span>
              <el-button
                text
                size="small"
                @click="showTitleOptions = false"
              >
                <el-icon><Close /></el-icon>
              </el-button>
            </div>
            <div class="title-options-list">
              <div
                v-for="(title, index) in recommendedTitles"
                :key="index"
                class="title-option"
                @click="selectTitle(title)"
              >
                {{ title }}
              </div>
              <div v-if="recommendedTitles.length === 0" class="no-titles">
                暂无推荐标题
              </div>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="15"
            placeholder="请输入帖子内容..."
            maxlength="5000"
            show-word-limit
            resize="vertical"
          />
        </el-form-item>

        <el-form-item>
          <div class="form-actions">
            <el-button @click="handleCancel">取消</el-button>
            <el-button 
              type="primary" 
              @click="handleSubmit"
              :loading="loading"
            >
              {{ loading ? '发布中...' : '发布帖子' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 发布提示 -->
    <el-card class="tips-card">
      <template #header>
        <div class="tips-header">
          <el-icon><InfoFilled /></el-icon>
          <span>发布提示</span>
        </div>
      </template>
      <div class="tips-content">
        <ul>
          <li>标题应该简洁明了，能够概括帖子主要内容</li>
          <li>内容应该详细完整，便于其他用户理解和讨论</li>
          <li>请遵守社区规范，不发布违规内容</li>
          <li>支持 Markdown 格式，可以使用代码块、列表等</li>
          <li>发布后可以随时编辑和修改</li>
        </ul>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.create-post {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  box-sizing: border-box;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 2.5em;
  font-weight: bold;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 1.1em;
}

.form-card {
  margin-bottom: 20px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.post-form {
  max-width: 100%;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.tips-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.tips-header {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #409eff;
  font-weight: 500;
}

.tips-content ul {
  margin: 0;
  padding-left: 20px;
  color: #666;
  line-height: 1.8;
}

.tips-content li {
  margin: 8px 0;
}

/* 智能标题相关样式 */
.title-input-container {
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.title-input {
  flex: 1;
}

.smart-title-btn {
  white-space: nowrap;
  min-width: 100px;
}

.title-options {
  margin-top: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.title-options-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #e4e7ed;
  background: #f8f9fa;
  font-weight: 500;
  color: #333;
}

.title-options-list {
  max-height: 200px;
  overflow-y: auto;
}

.title-option {
  padding: 12px 16px;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.2s;
  color: #333;
  line-height: 1.5;
}

.title-option:hover {
  background-color: #f5f7fa;
}

.title-option:last-child {
  border-bottom: none;
}

.no-titles {
  padding: 20px 16px;
  text-align: center;
  color: #999;
  font-style: italic;
}

@media (max-width: 768px) {
  .page-header h1 {
    font-size: 2em;
  }
  
  .form-actions {
    flex-direction: column;
    gap: 10px;
  }
  
  .form-actions .el-button {
    width: 100%;
  }
  
  .title-input-container {
    flex-direction: column;
    gap: 8px;
  }
  
  .smart-title-btn {
    width: 100%;
  }
}
</style>